<template>
  <view class="navigation">
    <eui-navbar ref="EuiNavBar" :title="title" displayable="true" color="#000000" backgroundColor="#FFFFFF" rightIcon=""/>
    <view class="main-view" :style="{ height: scrollHeight + 'rpx' }">
      <scroll-view scroll-y="true" style="height: 100%;">
        <eui-card title="任务类型" :showTitleLine="true" topMargin="0">
          <eui-card-input v-model="formData.c_name" title="任务名称" placeholder="请输入任务名称" h-padding="0"
                          type="text" maxlength="50" :required="true"/>
          <eui-card-input v-model="formData.c_role_code" title="目标角色" :range="selectRange.roleList"
                          placeholder="" h-padding="0" type="selector" rightIconType="right" />
          <eui-card-input v-model="formData.c_property" title="任务性质" :range="selectRange.propertyList"
                          placeholder="请选择性质" h-padding="0" type="selector" rightIconType="right"
                          :required="true"/>
          <eui-card-input v-model="formData.c_level" title="任务等级" :range="selectRange.levelList"
                          placeholder="请选择等级" h-padding="0" type="selector" rightIconType="right"
                          :required="true"/>
          <eui-card-input v-model="formData.c_importance" title="重要性" :range="selectRange.importanceList"
                          placeholder="请选择重要性" h-padding="0" type="selector" rightIconType="right"
                          :required="true"/>
          <eui-card-input v-model="formData.c_timeliness" title="时效性" :range="selectRange.timelinessList"
                          placeholder="请选择时效性" h-padding="0" type="selector" rightIconType="right"
                          :required="true"/>
        </eui-card>
        <eui-card title="控制属性" :showTitleLine="true">
          <eui-card-input v-model="formData.c_is_match_store" title="匹配在店" h-padding="0" type="switch" :required="true" />
          <eui-card-input v-model="formData.c_exclude" title="是否排它" h-padding="0" type="switch" :required="true" />
          <eui-card-input v-model="formData.c_must_upload_complate_img" title="上传图片" h-padding="0" type="switch" />
          <eui-card-input v-model="formData.c_time" title="预估用时（分钟）" h-padding="0" type="number"
                          ref="inputCostTime" rightIconType="" placeholder="请输入预估用时" :required="true"
                          @confirm="costTimeFunc" isBlur :titleWidth="245" maxlength="8"/>
          <eui-card-input v-model="formData.c_distribute_mode" title="分配方式" :range="selectRange.distributeList"
                          placeholder="请选择分配方式" h-padding="0" type="selector" rightIconType="right"
                          :required="true"/>
          <eui-card-input v-model="formData.c_recv_adno" title="接收部门" h-padding="0" type="textname2"
                          :name="getName('rdsDeparts', formData.c_recv_adno)" ref="cardAdnoInput"
                          rightIconType="right" @iconClick="clickRight('c_adno')"  placeholder="" />
          <eui-card-input v-model="formData.c_metering_method" title="计量方式" :range="selectRange.meteringList" placement="top"
                          placeholder="请选择计量方式" h-padding="0" type="selector" rightIconType="right" @buttonClick="cardInputMeterMethod" />
          <eui-card-input v-model="formData.c_unit" :displayable="formData.c_metering_method === 'M0'" title="单位" :range="selectRange.unitList"
                          placeholder="" h-padding="0" type="selector" rightIconType="right" placement="top" />
        </eui-card>
      </scroll-view>
    </view>
    <view class="bottom-view">
      <eui-button type="primary" title="保存" singleTag="保存" @buttonClick="confirm" />
      <!--      <eui-button type="primary" title="关闭任务" singleTag="发布" :useCustom="true" buttonColor="#FFFFFF" borderColor="#FFFFFF" @buttonClick="confirm" />-->
    </view>
  </view>
</template>

<script setup type="ts">
import { storeToRefs } from 'pinia';
import {computed, onMounted, ref} from "vue";
import {onLoad} from "@dcloudio/uni-app";
import {getRdsSysConfig, init} from "@/hooks/init";
import { getRelatedName, getDictName, getUserDictSelectList, getDictSelect, getDictSelectList, getWeightUnits, getDictList } from '../../components/RelatedName.js';
import Enjoy from "@/common/enjoy";
import { getRdsUrl, rdsRequest } from "@/hooks/rdsServices";
import {useMainStore} from "@/store/modules/store";
import {useLoginStore} from "@/store/modules/useLoginStore";
import TaskGround from '../components/taskGroup.vue'
import dayjs from 'dayjs';
import Guid from '@/common/guid';
import service from "@/common/service";
import useService from '@/hooks/useService';
import useUpload from "@/hooks/useUpload";
import { useThemeStore } from '@/store/themeStore';
import dateRangUtil from "@/common/dateRangUtil";
const themeStore = useThemeStore(); // 主题
const { theme } = storeToRefs(themeStore);

const mainService = useService({ prefix: "mainApi" });
const { upload, remove, fetchFile } = useUpload({ prefix: 'mainApi' });
const rdsUrl = getRdsUrl();
const mainStore = useMainStore();
const { loginInfo } = mainStore;
const LoginStore = useLoginStore();

const scrollHeight = ref(0);
const title = ref('任务设置');
// 工单数据
const formData = ref({
  // 任务类型
  c_name: "", // 任务名称
  c_role_code: "", // 目标角色
  c_property: "P0", // 任务性质
  c_level: "1", // 任务角色等级
  c_importance: "I0", // 任务重要性
  c_timeliness: "T0", // 任务时效性
  // 控制属性
  c_is_match_store: false, // 是否匹配在店
  c_exclude: false, // 是否排它 0:否 1:是
  c_must_upload_complate_img: false, // 任务完成是否必须上传图片
  c_time: 30, // 预估用时(分钟)
  c_distribute_mode: "D0", // 任务分配方式
  c_recv_adno: "", // 部门
  c_recv_adno_name: "",
  c_metering_method: "M0", // 任务计量方式
  c_unit: "", // 任务计量单位
  // 预留
  c_guid: "",
  c_mk_dt: "",
  c_mk_userno: "",
  c_modify_dt: "",
  c_modify_userno: "",
  c_name_en: "",
  c_recv_userno: "",
  c_source: "", // S1
  c_store_id: "",
});
const selectRange = ref({
  roleList: [], // 目标角色
  propertyList: [], // 性质
  importanceList: [], // 重要性
  timelinessList: [], // 时效性
  levelList: [], // 等级
  distributeList: [], // 分配方式
  meteringList: [], // 计量方式
  unitList: [], // 单位
})



// 获取列表高度
const getListHeight = async () => {
  await uni.getSystemInfo({
    success: function (res) {
      let info = uni.createSelectorQuery().select(".main-view");
      info.boundingClientRect(function (data) {
        //获取列表高度
        let height = res.windowHeight - data.top;
        //转换rpx
        scrollHeight.value = height / (res.windowWidth / 750) - 180;
      }).exec()
    }
  });
};

// 获取字典
const getSysConfig = async () => {
  selectRange.value.propertyList = getDictSelectList('任务性质');
  selectRange.value.importanceList = getDictSelectList('任务重要性');
  selectRange.value.timelinessList = getDictSelectList('任务时效性');
  selectRange.value.levelList = getDictSelectList('任务角色等级');
  selectRange.value.distributeList = getDictSelectList('任务分配方式');
  selectRange.value.meteringList = getDictSelectList('任务计量方式');
  selectRange.value.unitList = getDictSelectList('任务计量单位');
}

// 获取目标角色
const getUserRole = async () => {
  const result = await rdsRequest(rdsUrl.mainApi, 'taskdefine', 'FetchTaskRoles', '');
  if (result && result.length > 0) {
    selectRange.value.roleList = result.map(item => ({
      text: item.Name,
      value: item.Code,
    }));
  }
}

onMounted((e) => {
  getListHeight()
});

onLoad(async (option) => {
  service.enjoyShowLoading('正在加载...');
  await getUserRole();
  await getSysConfig();
  if (option.taskId) {
    formData.value.c_guid = option.taskId;
    title.value = option.taskName;
    await billQuery();
  } else {
    formData.value.c_guid = Guid.NewGuid().ToString();
  }
  service.enjoyHideLoading();
})

// 数据查询
const billQuery= async () => {
  service.enjoyShowLoading('正在加载...');
  const req = formData.value.c_guid;
  const result = await rdsRequest(rdsUrl.mainApi, 'taskdefine', 'FetchTaskData', req);
  service.enjoyHideLoading();
  if (result) {
    formData.value = {
      ...result,
      c_is_match_store: result.c_is_match_store === '1', // 是否匹配在店
      c_exclude: result.c_exclude === '1', // 是否排它
      c_must_upload_complate_img: result.c_must_upload_complate_img === '1', // 任务完成是否必须上传图片
    }
  } else {

  }
}

// 选择框点击事件
const clickRight = (type) => {
  let parms = Enjoy.GetDialogParms();
  parms.CallBack = SelectionChanged;
  if (type == 'c_store_id') {
    parms.SelectionType = "机构选择";
  } else if (type == 'c_adno') {
    parms.SelectionType = "部门选择";
    parms.SelectedItems = formData.value.c_recv_adno;
  } else if (type == 'c_wno') {
    parms.SelectionType = "仓库选择";
  }
  Enjoy.OpenDialog(parms)
}

const SelectionChanged = async (e) => {
  if (e.SelectionType=='部门选择') {
    formData.value.c_recv_adno = e.BackParms.Key;
    formData.value.c_recv_adno_name = e.BackParms.Value;
  }
}

// 校验预估用时
const costTimeFunc = () => {
  let { c_time } = formData.value;
  console.log('====c_time: ', c_time);
}

// 选择计量方式
const cardInputMeterMethod = (e) => {
  // 计时不用选择单位
  if (e === 'M0') {
    formData.value.c_unit = '';
  }
}

// 底部按钮点击事件
const confirm = async () => {
  const { c_name, c_time } = formData.value;
  if (!c_name) {
    uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '任务名称不能为空！'
    });
    return
  }
  let num = parseFloat(c_time)
  if (isNaN(num) || num < 30) {
    uni.showToast({
      duration: 3500,
      icon: 'none',
      title: '预估用时（分钟）不能小于 30'
    });
    return
  }
  service.enjoyShowLoading('保存中...');
  const objectData = {
    ...formData.value,
    c_mk_dt: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    c_mk_userno: loginInfo.sUser,
    c_modify_dt: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    c_modify_userno: loginInfo.sUser,
    c_source: formData.value.c_source ? formData.value.c_source : 'S1',
    c_exclude: formData.value.c_exclude ? '1' : '0', // 是否排它 0:否 1:是
    c_is_match_store: formData.value.c_is_match_store ? '1' : '0', // 是否匹配在店
    c_must_upload_complate_img: formData.value.c_must_upload_complate_img ? '1' : '0', // 任务完成是否必须上传图片
  };
  const result = await rdsRequest(rdsUrl.mainApi, 'taskdefine', 'UpdateTask', objectData);
  service.enjoyHideLoading();
  uni.showToast({
    duration: 2000,
    icon: 'none',
    title: '保存成功'
  });
  // 返回并刷新
  let pages = getCurrentPages();
  let prevPage = pages[pages.length - 2];
  uni.navigateBack({
    delta: 1,
    success: () => {
      if (prevPage && prevPage.$vm) {
        setTimeout(() => {
          prevPage.$vm.$.exposed.updateTaskList();
        }, 500);
      } else {
        console.error('Error: Previous page or method not found.');
      }
    },
    fail: (error) => {
      console.error('Navigation failed:', error);
    }
  });
}

const getName = (key, value) => {
  if (!value) {
    return ''
  }
  let list = [];
  value.split(',').map(item => {
    list.push("[" + item + "]" + (getRelatedName(key, item) || key));
  })
  return list.join(',');
}

</script>

<style lang="scss" scoped>
@import '@/main.scss';

.navigation {
  display: flex;
  height: 100vh;
  width: 100%;
  flex-direction: column;
  background: #F2F2F2;
}

.main-view {
  width: 100%;
  margin-top: 20rpx;
  display: flex;
  position: relative;
}

.bottom-view {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 160rpx;
  margin-top: 20rpx;
  box-sizing: border-box;
  padding: 40rpx;
}


</style>
